<?php

namespace app\api\model\cps;



use app\api\model\ExtendConsume;
use app\api\model\UserConsumeLog;
use app\common\model\User;
use app\shopapi\model\ExtendConsumeShop;

require_once ROOT_PATH.'extend/jd_open_api/jd/JdClient.php';
require_once ROOT_PATH.'extend/jd_open_api/jd/request/UnionOpenGoodsQueryRequest.php';
require_once ROOT_PATH.'extend/jd_open_api/jd/request/domain/UnionOpenGoodsQuery/GoodsReqDTO.php';
require_once ROOT_PATH.'extend/jd_open_api/jd/request/UnionOpenCategoryGoodsGetRequest.php';
require_once ROOT_PATH.'extend/jd_open_api/jd/request/UnionOpenGoodsMaterialQueryRequest.php';
require_once ROOT_PATH.'extend/jd_open_api/jd/request/domain/UnionOpenGoodsMaterialQuery/GoodsReq.php';
require_once ROOT_PATH.'extend/jd_open_api/jd/request/UnionOpenGoodsBigfieldQueryRequest.php';
require_once ROOT_PATH.'extend/jd_open_api/jd/request/UnionOpenCouponQueryRequest.php';
require_once ROOT_PATH.'extend/jd_open_api/jd/request/UnionOpenPromotionCommonGetRequest.php';
require_once ROOT_PATH.'extend/jd_open_api/jd/request/UnionOpenPromotionBysubunionidGetRequest.php';
require_once ROOT_PATH.'extend/jd_open_api/jd/request/UnionOpenOrderRowQueryRequest.php';
require_once ROOT_PATH.'extend/jd_open_api/jd/request/UnionOpenOrderBonusQueryRequest.php';
require_once ROOT_PATH.'extend/jd_open_api/jd/request/UnionOpenActivityQueryRequest.php';


class Jd
{

    protected $key = 'c4cee6b2d22065716dc21982af46451099d5fd6bf35a932df194b255d8b4b4b10109eb5c4b8454f4';

    protected $url = 'https://api.jd.com/routerjson';

    protected $id = '2034930634';

    protected $appKey = '6e5bc5bd51cd81fc3e9bfa0da3c0833d';

    protected $appSecret = 'b7a1b31179634fee99be13b9b6b44a8f';

    //关键词查询商品
    public function searchGoods($page,$keyword,$cid1)
    {
        $c = new \JdClient();
        $c->appKey = $this->appKey;
        $c->appSecret = $this->appSecret;
        //$c->accessToken = accessToken;
        //$c->serverUrl = SERVER_URL;
        $req = new \UnionOpenGoodsQueryRequest();
        //$goodsReqDTO= new GoodsReqDTO();
        $goodsReqDTO = [
            'pageIndex'=>$page,
        ];
        if ($keyword)$goodsReqDTO['keyword'] = $keyword;
        if ($cid1)$goodsReqDTO['cid1'] = $cid1;
        $req->setGoodsReqDTO($goodsReqDTO);
        //$req->setVersion("1.0");
        $resp = $c->execute($req, $c->accessToken);

        if (isset($resp->error_response)){
            throw new \Exception($resp->error_response->zh_desc);
        } else {
            //$resp = json_decode($resp,true);

            $result = json_decode($resp->jd_union_open_goods_query_responce->queryResult,true);

            if ($result['code']==200){
                if (isset($result['data'])){
                    foreach ($result['data'] as $k=>$v){
                        $result['data'][$k]['commissionInfo']['wawa_commission'] = round($v['commissionInfo']['couponCommission']*0.56,2);
                    }
                    return $result['data'];
                } else {
                    return [];
                }

            } else {
                throw new \Exception($result['message']);
            }
        }

    }

    //商品类目查询接口
    public function categoryGoods($parentId=0,$grade=0)
    {
        $c = new \JdClient();
        $c->appKey = $this->appKey;
        $c->appSecret = $this->appSecret;
        $req = new \UnionOpenCategoryGoodsGetRequest();
        $params = [
            'parentId'=>$parentId,
            'grade'=>$grade
        ];
        $req->setReq($params);
        $req->setVersion("1.0");
        $resp = $c->execute($req, $c->accessToken);
        $result = json_decode($resp->jd_union_open_category_goods_get_responce->getResult,true);
        if ($result['code']==200){
            return $result['data'];
        } else {
            throw new \Exception($result['message']);
        }
    }

    //猜你喜欢商品推荐
    public function recommendGoods($pageIndex=1,$eliteId=1)
    {
        $c = new \JdClient();
        $c->appKey = $this->appKey;
        $c->appSecret = $this->appSecret;

        $req = new \UnionOpenGoodsMaterialQueryRequest();

        $goodsReq = [
            'eliteId'=>$eliteId,
            'pageIndex'=>$pageIndex,
            'pageSize'=>10
        ];
        $req->setGoodsReq($goodsReq);
        $req->setVersion("1.0");
        $resp = $c->execute($req, $c->accessToken);

        $result = json_decode($resp->jd_union_open_goods_material_query_responce->queryResult,true);
        if ($result['code']==200){
            foreach ($result['data'] as $k=>$v){
                $result['data'][$k]['commissionInfo']['wawa_commission'] = round($v['commissionInfo']['couponCommission']*0.56,2);
            }
            return $result['data'];
        } else {
            throw new \Exception($result['message']);
        }
    }

    //商品详情查询接口
    public function goodsDetail($skuIds)
    {
        $c = new \JdClient();
        $c->appKey = $this->appKey;
        $c->appSecret = $this->appSecret;

        $req = new \UnionOpenGoodsBigfieldQueryRequest();
        //$goodsReq= new GoodsReq;
        $goodsReq = [
            'skuIds'=>[$skuIds],
            //'sceneId'=>1
        ];

        $req->setGoodsReq($goodsReq);

        $resp = $c->execute($req, $c->accessToken);
        if (isset($resp->error_response->code)){
            throw new \Exception($resp->error_response->zh_desc);
        } else {

            $result = json_decode($resp->jd_union_open_goods_bigfield_query_responce->queryResult,true);

            if ($result['code']==200){
                /*foreach ($result['data'] as $k=>$v){
                    $result['data'][$k]['baseBigFieldInfo']['propGroups'] = json_decode($v['baseBigFieldInfo']['propGroups']);
                }*/

                return $result['data'];
            } else {
                throw new \Exception($result['message']);
            }
        }

    }

    //优惠券领取情况查询接口
    public function couponInfo($coupon)
    {
        $c = new \JdClient();
        $c->appKey = $this->appKey;
        $c->appSecret = $this->appSecret;

        $req = new \UnionOpenCouponQueryRequest();
        $couponUrls= array($coupon);
        $req->setCouponUrls($couponUrls);

        $resp = $c->execute($req, $c->accessToken);

        $result = json_decode($resp->jd_union_open_coupon_query_responce->queryResult,true);
        if ($result['code']==200){
            return $result['data'];
        } else {
            throw new \Exception($result['message']);
        }
    }

    //网站/APP/流量媒体获取url
    public function getUrl($materialId)
    {
        $c = new \JdClient();
        $c->appKey = $this->appKey;
        $c->appSecret = $this->appSecret;

        $req = new \UnionOpenPromotionCommonGetRequest();
        //$promotionCodeReq= new PromotionCodeReq;
        $promotionCodeReq = [
            'materialId'=>$materialId,
            //'siteId'=>'4101285673',
            'sceneId'=>1
        ];

        $req->setPromotionCodeReq($promotionCodeReq);
        $req->setVersion("1.0");
        $resp = $c->execute($req, $c->accessToken);

        $result = json_decode($resp->jd_union_open_promotion_common_get_responce->getResult,true);
        if ($result['code']==200){
            return $result['data'];
        } else {
            throw new \Exception($result['message']);
        }
    }

    //小程序url
    public function getWeappUrl($materialId,$user_id,$couponUrl)
    {
        $user = User::get($user_id);

        $c = new \JdClient();
        $c->appKey = $this->appKey;
        $c->appSecret = $this->appSecret;

        $req = new \UnionOpenPromotionBysubunionidGetRequest();
        //$promotionCodeReq= new PromotionCodeReq;
        $promotionCodeReq = [
            'materialId'=>$materialId,
            'subUnionId'=>$user->mobile.'_'.$user_id,
            'couponUrl'=>$couponUrl
            //'sceneId'=>1
        ];

        $req->setPromotionCodeReq($promotionCodeReq);
        $resp = $c->execute($req, $c->accessToken);

        $result = json_decode($resp->jd_union_open_promotion_bysubunionid_get_responce->getResult,true);
        if ($result['code']==200){
            return $result['data'];
        } else {
            throw new \Exception($result['message']);
        }
    }

    //奖励订单查询
    public function commission_order_list($page)
    {
        $c = new \JdClient();
        $c->appKey = $this->appKey;
        $c->appSecret = $this->appSecret;

        $req = new \UnionOpenOrderBonusQueryRequest();

        $orderReq= [
            'optType'=>1,
            'startTime'=>time()-10,
            'endTime'=>time(),
            'pageNo'=>$page,
            'pageSize'=>100,
            //'sortValue'=>'',
        ];

        $req->setOrderReq($orderReq);
        $req->setVersion("1.0");
        $resp = $c->execute($req, $c->accessToken);
        $result = json_decode($resp->jd_union_open_order_bonus_query_responce->queryResult,true);
        if ($result['code']==200){
            return $result['data'];
        } else {
            throw new \Exception($result['message']);
        }
    }

    //
    public function activitySearch($page)
    {
        $c = new \JdClient();
        $c->appKey = $this->appKey;
        $c->appSecret = $this->appSecret;

        $req = new \UnionOpenActivityQueryRequest();
        $activityReq=[
            'page'=>$page
        ];
        $req->setActivityReq($activityReq);
        $req->setVersion("1.0");
        $resp = $c->execute($req, $c->accessToken);
        $result = json_decode($resp->jd_union_open_activity_query_responce->queryResult,true);
        if ($result['code']==200){
            return $result['data'];
        } else {
            throw new \Exception($result['message']);
        }

    }

    //查询未结算的订单
    public function unliquidated()
    {
        $lists = UserConsumeLog::where(['cps_type'=>0,'consume_type'=>2,'is_to_account'=>0,'is_common'=>0,'is_refund'=>0])
            ->field('pay_time')->select();

        foreach ($lists as $k=>$v){
            $start = date('Y-m-d H:i:s',$v['pay_time']-3600);
            $end = date('Y-m-d H:i:s',$v['pay_time']);
            $res = $this->orderlist(1,$start,$end);
        }
    }


    //查询推广订单及佣金信息
    public function orderlist($type=0,$start='',$end='')
    {
        $c = new \JdClient();
        $c->appKey = $this->appKey;
        $c->appSecret = $this->appSecret;

        $req = new \UnionOpenOrderRowQueryRequest();

        $startTime = date('Y-m-d H:i:s',time()-3600);
        $endTime = date('Y-m-d H:i:s',time());

        if ($type==1){
            $startTime = $start;
            $endTime = $end;
        }

        $orderReq = [
            'pageIndex'=>1,
            'pageSize'=>500,
            'type'=>1,
            'startTime'=>$startTime,
            'endTime'=>$endTime,
            'fields'=>'goodsInfo'
        ];


        $req->setOrderReq($orderReq);

        $resp = $c->execute($req, $c->accessToken);

        $result = json_decode($resp->jd_union_open_order_row_query_responce->queryResult,true);

        if ($result['code']==200){
            if (array_key_exists('data',$result)){
                foreach ($result['data'] as $k=>$v){

                    if ($v['subUnionId']){
                        $subUnionId = explode('_',$v['subUnionId']);

                        $user = User::get(['id'=>$subUnionId[1]]);
                        if ($user){

                            $consume_log_info = UserConsumeLog::get([ 'user_id'=>$user->id, 'order_no'=>$v['orderId'],'goods_id'=>$v['goodsInfo']['productId']]);

                            $estimateFee = $v['estimateFee'];
                            $commission = $estimateFee*0.56;

                            if (!$consume_log_info){
                                $consume_log_model = new UserConsumeLog();

                                $consume_log_data = [
                                    'user_id'=>$user->id,
                                    'title'=>$v['skuName'],
                                    'shop_id'=>$v['goodsInfo']['shopId'],
                                    'shop_name'=>$v['goodsInfo']['shopName'],
                                    'image'=>$v['goodsInfo']['imageUrl'],
                                    'order_no'=>$v['orderId'],
                                    'pay_time'=>strtotime($v['orderTime']),
                                    'pay_price'=>$v['estimateCosPrice'],
                                    'consume_type'=>2,
                                    'cps_type'=>0,
                                    'goods_id'=>$v['goodsInfo']['productId'],
                                    'commission'=>$commission,
                                    'total_commission'=>$estimateFee,
                                    'order_status_name'=>'已付款'
                                ];

                                User::update(['is_buy'=>1],['id'=>$user->id]);
                                $user_model = new User();

                                $user_model->upgrade($user->id);
                                $consume_log_model->save($consume_log_data);
                                UserConsumeLog::lockMemberConsumeCalculate($user->id,$consume_log_model->total_commission,$consume_log_model->consume_id,0);
                                UserConsumeLog::newrecommendShopConsumeCalculate($user->id,0,$consume_log_model->total_commission,$consume_log_model->consume_id,2);
                            } else {
                                $payMonth = strtotime($v['payMonth']);

                                if ($v['validCode']==17&&time()>$payMonth&&$consume_log_info->is_to_account==0){
                                    //发放消费记录的收益
                                    UserConsumeLog::sendCommission($consume_log_info->order_no,$consume_log_info->goods_id);
                                } elseif($v['validCode']==3&&$consume_log_info->is_refund==0) {
                                    $consume_log_info->commission = 0;
                                    $consume_log_info->order_status_name = '退款成功';
                                    $consume_log_info->is_refund = 1;
                                    $consume_log_info->save();
                                    ExtendConsume::update(['commission'=>0],['consume_log_id'=>$consume_log_info->consume_id]);
                                    ExtendConsumeShop::update(['commission'=>0],['consume_log_id'=>$consume_log_info->consume_id]);
                                }

                            }
                        }

                    }


                }
                return $result['data'];
            } else {
                return [];
            }

        } else {
            throw new \Exception($result['message']);
        }
    }


    public function urllist()
    {
        $data = [
            'zhuanpan'=>'https://u.jd.com/M6GAPGG',
            'miaosha'=>'https://u.jd.com/MaGnrEW',
            'youhui'=>'https://u.jd.com/MGGgNC5',
            'remai'=>'https://u.jd.com/MOGOCwb',
            'rexiao'=>'https://u.jd.com/M1GPQLh'
        ];
        return $data;
    }
}